<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
Class Mrestaurant extends MY_Model
{
    public function __construct()
    {
        parent::__construct();
    }
   
    public function getRetaurantDB($number,$offset)
    {
        //die($this->session->userdata('admin_id').'');
        $limit = $offset ? intval($offset) : '0';
        $sql = "SELECT r.id, r.`name`, r.name_ascii, r.image, r.logo, r.active, r.admin_id, r.image_thumb, r.created, r.manage_id FROM restaurant AS r WHERE r.manage_id = ".$this->session->userdata('admin_id')." ";
        $key = $this->getParamString('keyword');
        if(!in_array($key, array(null, '', '0')))
        {
            $sql .= " AND (r.`name` like '%%".$key."%%' OR ";
            $sql .= " r.name_ascii like '%%".$key."%%') ";
        }
        $sql .= "ORDER BY r.orderby ASC";
        $xdata = " LIMIT ".$limit.",".$number." ";
        //die(''.$sql.$xdata);
        $xs = $this->db->query($sql.$xdata)->result_object();
        //echo '<pre>';die(print_r($xs));
        foreach($xs AS $el=>$le)
        {
            $xs[$el]->zone = $this->db->query('SELECT z.title, z.title_ascii, z.id FROM restaurant AS r INNER JOIN restaurant_zone AS rz ON rz.id_restaurant = r.id INNER JOIN zone AS z ON z.id = rz.id_zone WHERE r.id = '.$le->id)->result_object();
            $xs[$el]->categories = $this->db->query('SELECT rc.id, rc.title, rc.title_ascii FROM restaurant AS r INNER JOIN restaurant_categories_key AS rck ON rck.id_restaurant = r.id  INNER JOIN restaurant_categories AS rc ON rc.id = rck.id_categories WHERE r.id = '.$le->id)->result_object();
			$data_review = $this->db->query('SELECT rr.star AS star 
			FROM restaurant AS r INNER JOIN restaurant_review AS rr ON rr.restaurant_id = r.id WHERE rr.improved = 1 AND r.id = '.$le->id)->result_object();
			$sum = 0; $dem = 0;
			foreach ( $data_review AS $al=>$la ){
				if ( !in_array($la->star,array('',null,0)) ){
					$sum += (int)$la->star;
					$dem++;
				}
			}
			if( $sum == 0 ){
				$xs[$el]->review = 0;
			}else{
				$xs[$el]->review = number_format(($sum/$dem),'2', ',', '.');
			}
			$xs[$el]->count_review = $dem;
        }
        //echo '<pre>'.die(print_r($xs));
        $count = $this->db->query($sql)->num_rows();
        return array('data' => $xs, 'count' => $count);
    }
    
    
    
    
    
    
    
    
    
    
    public function addRetaurantDb($admin_id, $img_1, $img_2, $img_3, $phone)//, $img_4)
    {
        $title = $this->getParamString('title');
        $title_ascii = $this->get_ascii($title);
        
        $arr = array(
                'name'                        => $title,
                'name_ascii'                  => $title_ascii,
                'logo'                         => $img_1,
                'image'                        => $img_2,
                //'share_facebook_image'         => $img_3,
                'hotline'                      => $img_3,
                'phone_hotline'                => $phone,
                //'share_facebook_title'         => $this->getParamString('share_facebook_title'),
                //'share_facebook_description'   => $this->getParamString('share_facebook_description'),
                'share_facebook_url'           => $this->getParamString('share_facebook_url'),
                'active'                       => $this->getParamInt('active'),
                'created'                      => date('Y-m-d H:i:s'),
                'admin_id'                     => $admin_id
            );
        $this->db->insert('restaurant', $arr);
        $id = $this->db->insert_id();
        $this->db->update('options', array('content' => time()), "tags = 'time_update_restaurant'");
        
        $categories = $this->getParamArray('categories');
        
        foreach($categories AS $le=>$el)
        {
            $c_cate = array('id_categories' => $el, 'id_restaurant' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
            
            $this->db->insert('restaurant_categories_key', $c_cate);
        }
        
        return 200;

    }
    
    
    public function editRetaurantDb($admin_id, $img_1, $img_2, $img_3, $id, $phone)//$img_4
    {
        $title = $this->getParamString('title');
        $title_ascii = $this->get_ascii($title);
        
        $arr = array(
                'name'                        => $title,
                'name_ascii'                  => $title_ascii,
                'phone_hotline'                => $phone,
                //'share_facebook_title'         => $this->getParamString('share_facebook_title'),
                //'share_facebook_description'   => $this->getParamString('share_facebook_description'),
                'share_facebook_url'           => $this->getParamString('share_facebook_url'),
                'active'                       => $this->getParamInt('active'),
                'created'                      => date('Y-m-d H:i:s'),
                'admin_id'                     => $admin_id
            );
        $img_old = $this->db->query('SELECT logo, image, share_facebook_image, hotline FROM restaurant WHERE id = '.$id)->row_object();
        if(!in_array($img_1, array(null, '', '0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$img_old->logo);
            $arr['logo'] = $img_1;
        }
        
        if(!in_array($img_2, array(null, '', '0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$img_old->image);
            $arr['image'] = $img_2;
        }
        
       /* if(!in_array($img_4, array(null, '', '0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$img_old->share_facebook_image);
            $arr['share_facebook_image'] = $img_4;
        }*/
        
        if(!in_array($img_3, array(null, '', '0')))
        {
            @unlink(PROJECT_PATH.'/data/'.$img_old->hotline);
            $arr['hotline'] = $img_3;
        }
        
        $this->db->update('restaurant', $arr, "id = ".$id);
        $this->db->delete('restaurant_categories_key', "id_restaurant = ".$id);
        $this->db->update('options', array('content' => time()), "tags = 'time_update_restaurant'");
        if ($this->db->affected_rows() > 0)
        {
            $categories = $this->getParamArray('categories');
            foreach($categories AS $le=>$el)
            {
                $c_cate = array('id_categories' => $el, 'id_restaurant' => $id, 'admin_id' => $admin_id, 'created' => date('Y-m-d H:i:s'));
                $this->db->insert('restaurant_categories_key', $c_cate);
            }
            return 200;
        } 
        return 200;
    }
    
    public function deleteRetaurantDB($id)
    {
        $data = $this->db->query("SELECT logo, image, share_facebook_image, hotline FROM restaurant WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')")->result_object();
        foreach($data AS $el=>$le)
        {
            @unlink(PROJECT_PATH.'/data/'.$le->logo);
            @unlink(PROJECT_PATH.'/data/'.$le->image);
            @unlink(PROJECT_PATH.'/data/'.$le->share_facebook_image);
            @unlink(PROJECT_PATH.'/data/'.$le->hotline);
        }
        $this->db->query("DELETE FROM restaurant WHERE id IN ('" . (is_array($id) ? implode("','", $id) : $id) . "')");
        $this->db->update('options', array('content' => time()), "tags = 'time_update_restaurant'");
        return 200;
    }
    
    public function getRetaurantCategoriesDetailDB($id)
    {
        return $this->db->query('SELECT * FROM restaurant_categories WHERE id = '.$id)->row_object();
    }
    
    
    
    public function optioncountry($id)
    {
        $data = $this->db->query('SELECT id, title FROM country ORDER BY title ASC')->result_object();
        $html = '<option value = "">Chọn quốc gia</option>';
        foreach($data AS $el=>$le)
        {
            if($le->id == $id)
            {
                $selected = 'selected="selected"';
            }else{
                $selected = '';
            }
            $html .= '<option value="'.$le->id.'" '.$selected.'>'.$le->title.'</option>';
        }
        return $html;
    }
    
    public function optionRestauRantZone($id)
    {
        $data = $this->db->query('SELECT id, title FROM zone ORDER BY title ASC')->result_object();
        $html = '<option value = "">Chọn khu vực</option>';
        foreach($data AS $el=>$le)
        {
            if($le->id == $id)
            {
                $selected = 'selected="selected"';
            }else{
                $selected = '';
            }
            $html .= '<option value="'.$le->id.'" '.$selected.'>'.$le->title.'</option>';
        }
        return $html;
    }
    
    
    
    public function danhmucGroupotp($selected = '')
    {
        $html = '';$selecteds = '';
    	$gRs = $this->db->query("SELECT * FROM restaurant_categories WHERE parent_id = 0 ORDER BY id ASC")->result_array();
        if($gRs)
        {
            $child = '|--';
            foreach ($gRs As $gel)
        	{
					if(is_array($selected))
					{ 
						foreach($selected AS $el=>$le)
						{
							if($le['id'] == $gel['id'])
							{
								$selecteds = 'selected="selected"';
							}
						}
					}
			
					$check_parent = $this->db->query('SELECT id FROM restaurant_categories WHERE parent_id = '.$gel['id'])->num_rows();
					if($check_parent > 0)
					{
						$html .= ' <optgroup label="' . $gel['title'] .'" style="font-weight: bold;color: #16708A">fdasfdsf';
						$html .= $this->subdanhmucGroupotp($selected, $gel['id'], $child);
						$html .= '</optgroup>';
					}else{
						$html .= '<option value="' . $gel['id'] . '" '.$selecteds;
						$html .= '>' . $child .' '. $gel['title'] . '</option>';
						$html .= $this->subdanhmucGroupotp($selected, $gel['id'], $child);
					}
    	    		
        	}
        }
        return $html;
    }
    private function subdanhmucGroupotp($selected, $parent,$child)
    {
        
        $child = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$child;
        $htmls = '';
        $selecteds = '';
        $gGs = $this->db->query("SELECT * FROM restaurant_categories WHERE parent_id = '".$parent."' ORDER BY id ASC")->result_array();
        foreach ($gGs As $key=>$val)
		{
		  
            if(is_array($selected))
            {   
                foreach($selected AS $el=>$le)
                {
                    if($le['id'] == $val['id'])
                    {
                        $selecteds = 'selected="selected"';
                    }
                }
            }
            
            
            $check_parent = $this->db->query('SELECT id FROM restaurant_categories WHERE parent_id = '.$val['id'])->num_rows();
            if($check_parent > 0)
            {
                $htmls .= ' <optgroup label="&nbsp;&nbsp;' . $child .' ' . $val['title'] .'" style="font-weight: bold;color: #16708A">
                ';
                $htmls .= $this->subdanhmucGroupotp($selected, $val['id'], $child);
                $htmls .= '</optgroup>';
            }else{
                //echo $selecteds.'<br />';
                $htmls .= '<option value="' . $val['id'] . '" '.$selecteds;
            	$htmls .= '>' . $child .' '. $val['title'] . '</option>';
                $htmls .= $this->subdanhmucGroupotp($selected, $val['id'], $child);
            }

                
		}
        return $htmls;
    }
    
    
    public function getRestaurantDetailDB($id)
    {
        $sql = "SELECT r.* FROM restaurant AS r WHERE 1=1 ";
        
        $xdata = " AND r.id = ".$id;
        $xs = $this->db->query($sql.$xdata)->row_object();
        $xs->categories = $this->db->query('SELECT rck.id_categories AS id FROM restaurant AS r  INNER JOIN restaurant_categories_key AS rck ON rck.id_restaurant = r.id  WHERE r.id = '.$xs->id)->result_array();
        return $xs;  
    }
    
    
    public function sortLabalDb($arr)
    {
        $exp = explode(',' , substr($arr, 0, -1));
        foreach($exp AS $el=>$le)
        {
            $this->db->update('restaurant', array('orderby' => ($el+1)), "id = ".$le);
            $this->db->update('options', array('content' => time()), "tags = 'time_update_restaurant'");
        }
        return 'ok';
    }
    
}
